package com.roc.web.action.terminal;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.common.Excel2007TermFileProcessor;
import com.roc.common.FileProcessor;
import com.roc.page.BaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblInsInf;
import com.roc.pojo.YjPosInfo;
import com.roc.service.IMerchantServices;
import com.roc.service.ITerminalSnBatchSerice;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Component
@Scope("prototype")
@Namespace("/terminalSnBatchLeading")
public class TerminalSnBatchLeadingAction extends BaseAction {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 5839095974243472588L;

	private Logger logger=LogManager.getLogger(TerminalSnBatchLeadingAction.class);

	@Autowired 
	ITerminalSnBatchSerice  terminalSnBatchSerice;
	
	@Autowired 
	IMerchantServices merchantServices;
	
	@Autowired
	IorgService orgService;
	
	@Autowired
	private IPowerInfoService operatorService;
	
	private List<TblInsInf> orgList=new ArrayList<TblInsInf>();
	
	List<Map<String,String>> realList = new ArrayList<Map<String,String>>() ;
	
	private File upload;
	
	private YjPosInfo posInfo;
	
	private String msg;
	
	@Action(value = "terminalSnBatchLeadingJsp", results = { @Result(name = "success", location = "/pages/terminal/terminal_sn_batch_leading.jsp")
             })
	public String terminalSnBatchLeadingJspAction() throws Exception{
		Operators logingOperators = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		String loginId = String.valueOf(logingOperators.getId());
		
		if( !logingOperators.getRoleType().equals(Role.SYSTEM.getCode())  
				&& ! loginId.equals(Constant.SHOUDANSHIYEBU_ID)
				&& ! logingOperators.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode()) ) {
			addActionError("此登陆账号没有权限");
			return ERROR;
		}
		org();

		getRequest().setAttribute("brandMap",ConfigProperties.getSysDB1("TMNL_BRAND",true));
		getRequest().setAttribute("nameMap", new ArrayList<Map<String,Object>>());
		getRequest().setAttribute("typeMap", ConfigProperties.getSysDB1("Terminal_Type",true));
		
		// 查询所有一级代理商
	//	getRequest().setAttribute("oneAgentMap", getAllOneAgent());
		
		return SUCCESS;
	}
	
	@Action(value = "terminalSnBatchLeading", interceptorRefs = {
			@InterceptorRef(value = "token"),
			@InterceptorRef(value = "rocDefaultStack", params = {
					"fileUpload.allowedExtensions", "xlsx",
					"fileUpload.maximumSize", "100000000" }) }, results = { 
			@Result(location = "/message.jsp"),
			@Result(name = "error", location = "/error.jsp"),
			@Result(name = "invalid.token", location = "/error.jsp")
	    })
	public String terminalSnBatchLeadingAction() throws Exception{

		Operators loginOperators = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);

		String loginId = String.valueOf(loginOperators.getId());
		
		if( !loginOperators.getRoleType().equals(Role.SYSTEM.getCode())  
				&& ! loginId.equals(Constant.SHOUDANSHIYEBU_ID)
				&& ! loginOperators.getRoleType().equals(Role.WARE_HOUSE_LEAD.getCode()) ) {
			addActionError("此登陆账号没有权限");
			return ERROR;
		}
		
		if(upload == null){
			addActionMessage("请选择文件");
			return SUCCESS;
		}
		if(  "".equals(posInfo.getAgentId()) || posInfo.getAgentId() <= 0 ){
			addActionMessage("请选择代理商");
			return SUCCESS;
		}
		try {
		//	org();
			
			FileProcessor processor = new Excel2007TermFileProcessor();
			List<YjPosInfo> posInfoImport = (List<YjPosInfo>) processor.process(upload);
			if(posInfoImport==null||posInfoImport.size()==0){
	        	addActionMessage("导入的Execl文件中不存在数据或文件格式不对，请确认!");
	        	return SUCCESS;
	        }
	        if(posInfoImport.size()>Constance.POS_SN_MAX_SIZE){
	        	addActionMessage("单批次导入最大记录为【"+Constance.POS_SN_MAX_SIZE+"】条，请分批导入！！！");
				return SUCCESS;
	        }
	        List<YjPosInfo> repeatList = getDeleteRepeatAgent(posInfoImport,posInfo);
	        if(repeatList!=null&&repeatList.size()>0){
	        	addActionMessage("导入的Execl文件中存在重复或sn号为空字符串或文字格式不对的记录，请确认!");
	        	getRequest().setAttribute("repeatList", repeatList);
	        	return SUCCESS;
	        }	
	        // 判断是否是同一个号段
	        List<YjPosInfo> unContList = getUnContSNInfo(posInfoImport,posInfo);
	        if(unContList != null && unContList.size() > 0){
	        	addActionMessage("导入的Execl文件中sn号不连续,不是同一个号段，请确认!");
	        	getRequest().setAttribute("repeatList", unContList);
	        	return SUCCESS;
	        }	
            repeatList= terminalSnBatchSerice.batchSaveSeriaNumInfo(posInfoImport, posInfo, loginOperators);
            if(repeatList!=null&&repeatList.size()>0){
            	addActionMessage("导入号段中有重复SN，不予处理，详见列表!");
            	getRequest().setAttribute("repeatList", repeatList);
				return SUCCESS;
	        }	 
            addActionMessage("操作员【"+loginOperators.getAccountNo()+"】选择的文件中，成功导入【"+(posInfoImport.size())+"】个");
            
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}
		
		return SUCCESS;
	}

	@Action(value = "queryRuleName",results={@Result(type="json",params={"root","realList"})} )
	public String queryRuleName()
	{
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");

		Operators loginOperators = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		
		try {
			String roleType = "02,03";
			List<Operators> agentList = operatorService.queryRealNameInfoByName(posInfo.getAgentName() ,loginOperators.getOrgCode(), roleType,1);
			if(agentList!=null)
			{
				Map<String,String> map = new HashMap<String, String>();
				for (Operators operators : agentList) {
					map = new HashMap<String, String>();
					
					map.put("id", String.valueOf(operators.getId()));
					map.put("accountNo", operators.getAccountNo());
					map.put("realName", operators.getRealName());
					
					realList.add(map);
				}
			}
			return SUCCESS;
		} catch (ServiceException e) {
			logger.error(e.getMessage(),e);
			addActionError("查询代理商名称失败！");
			return ERROR;
		} 
	}
	
	/**
     * 去除重复终端序列号数据
     * @param list
     * @return
     */
	private List<YjPosInfo> getDeleteRepeatAgent(List<YjPosInfo> list,YjPosInfo baseInfo){
		List<YjPosInfo>  repeatList = new ArrayList<YjPosInfo>();
		Map<String,YjPosInfo> map = new HashMap<String,YjPosInfo>();
		try {
			for(YjPosInfo posInfo:list){
				if(posInfo.getSerialNum()!=null && !"".equals(posInfo.getSerialNum())){
					if((null == posInfo.getSerialNum().trim() || "".equals(posInfo.getSerialNum().trim())) 
							|| map.containsKey(posInfo.getSerialNum())
							|| (!Utils.checkSnCode(posInfo.getSerialNum().trim()))){// 校验sn序列号格式
						String brandCode = baseInfo.getPosBrand();
						String typeCode = baseInfo.getPosType();
						String nameCode = baseInfo.getPosName();
						
						posInfo.setPosBrand(ConfigMerinfoUtil.getPosBRAND(brandCode));
						posInfo.setPosName(ConfigMerinfoUtil.getPosMODEL(nameCode , brandCode));
						posInfo.setPosType(ConfigMerinfoUtil.getTerminalType(typeCode));
						
						posInfo.setAgentId(baseInfo.getAgentId());
						repeatList.add(posInfo);
						continue;
					}
					map.put(posInfo.getSerialNum(), posInfo);
				} else {
					// 如果为空
					String brandCode = baseInfo.getPosBrand();
					String typeCode = baseInfo.getPosType();
					String nameCode = baseInfo.getPosName();
					
					posInfo.setPosBrand(ConfigMerinfoUtil.getPosBRAND(brandCode));
					posInfo.setPosName(ConfigMerinfoUtil.getPosMODEL(nameCode , brandCode));
					posInfo.setPosType(ConfigMerinfoUtil.getTerminalType(typeCode));
					
					posInfo.setAgentId(baseInfo.getAgentId());
					repeatList.add(posInfo);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}
		
		return repeatList;
	}
	
	private List<YjPosInfo> getUnContSNInfo(List<YjPosInfo> list,YjPosInfo baseInfo){
		List<YjPosInfo>  repeatList = new ArrayList<YjPosInfo>();
	//	Map<String,YjPosInfo> map = new HashMap<String,YjPosInfo>();
		try {
			// 取第一个SN序列号,作为一个连续号段的标准
			String oneSn = list.get(0).getSerialNum();
			// 第一个SN 的长度,
			int onelength = oneSn.length();
			// 取SN最后一个字符的位置,便于分割
			int r = Constance.getSNLastCharPlace(oneSn);
			String oneChars = "";
			if( r >= 0){
				oneChars = oneSn.substring(0, r+1);
			}
			
			String oneNumber = "";
			if ( r < (oneSn.length()-1) ){
				oneNumber = oneSn.substring( ( r== -1 ? 0 : r+1), oneSn.length() );
			}
			
			String lastNumber = oneNumber;
			
			for ( int i = 0; i < list.size() ; i++ ) {
				YjPosInfo info = list.get(i);
				// 
				boolean flag = true;
				
				String nextSn = info.getSerialNum();
				// 取当前SN最后一个字符的位置,避免到时候转换出错
				int nextPrace = Constance.getSNLastCharPlace(nextSn);
				// 如果 SN 长度相等 并且 最后一个字符的位置是一样的
				if(onelength == nextSn.length() && r == nextPrace ){

					String nextChars = "";
					if( r >= 0){
						nextChars = nextSn.substring(0, r+1);
					}
					String nextNumber = "";
					if ( r < (nextSn.length()-1) ){
						nextNumber = nextSn.substring(( r== -1 ? 0 : r+1), nextSn.length() );
					}
			//		System.out.println(r + ">>>" + nextChars + "^^^^" + nextNumber);
					if( i != 0){
						// 如果上一个SN和下一个SN 分割的前一段字符不相等 或者 后一段 数字的字符长度不相等,或者 前一个SN的数值+1 不等于 下一个SN的数值,说明 这不是一个连续的号段
						if( !oneChars.equals(nextChars) 
								|| oneNumber.length() != nextNumber.length() 
								|| (Long.parseLong(lastNumber) + 1) != (Long.parseLong(nextNumber)) ) {
							flag = false;
						}
					}
					lastNumber = nextNumber;
				}else{
					flag = false;
				}
				
				if(!flag){
					String brandCode = baseInfo.getPosBrand();
					String typeCode = baseInfo.getPosType();
					String nameCode = baseInfo.getPosName();
					
					info.setPosBrand(ConfigMerinfoUtil.getPosBRAND(brandCode));
					info.setPosName(ConfigMerinfoUtil.getPosMODEL(nameCode , brandCode));
					info.setPosType(ConfigMerinfoUtil.getTerminalType(typeCode));
					
				//	info.setAgentId(info.getAgentId());
					repeatList.add(info);
				}
				
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}
		
		return repeatList;
	}
    
	//查询机构
	public void org() throws Exception{
	//	Operators logingOperators = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
		TblInsInf inf = new TblInsInf();
		orgList=orgService.listOrg(inf);
			
	}

	public List<TblInsInf> getOrgList() {
		return orgList;
	}


	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	public List<Map<String, String>> getRealList() {
		return realList;
	}

	public void setRealList(List<Map<String, String>> realList) {
		this.realList = realList;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public YjPosInfo getPosInfo() {
		return posInfo;
	}

	public void setPosInfo(YjPosInfo posInfo) {
		this.posInfo = posInfo;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

}
